package com.comtime.usercenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.greendaodemo.AdminInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.service.MyService;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartbox.HBApplication;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.LogUtils;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.Util;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by MyPC on 2017/8/15.
 */

public class RemoteAddUserAvtivity extends BaseActivity {
    private String TAG = "RemoteAddUserAvtivity";

    EditText edt_phonenum;
    Spinner spinner;
    String selectedMac;
    MySharedPreferences mySharedPreferences;
    HBApplication application;
    DataBaseUtil dataBaseUtil;


    boolean isProgressing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_add_child);
        mySharedPreferences = MySharedPreferences.getInstance(this);
        application = (HBApplication) getApplication();
        dataBaseUtil = DataBaseUtil.getInstance(this);
        init();
        //regist();

    }

    /*void regist() {
        IntentFilter filter = new IntentFilter(
                MyService.ACTION_DISCONNECTED);
        filter.addAction(MyService.ACTION_ADD_USER_RESULT);
        registerReceiver(receiver, filter);
    }*/

    void init() {
        edt_phonenum = (EditText) findViewById(R.id.edt_phonenum);
        spinner = (Spinner) findViewById(R.id.spinner);
        ArrayList<AdminInfo> adminInfos = new ArrayList<AdminInfo>();
        final ArrayList<String> mMac = new ArrayList<String>();
        adminInfos = (ArrayList<AdminInfo>) dataBaseUtil.ShowAdminInfoByPhone(mySharedPreferences.getPhoneNum());

        for (AdminInfo info : adminInfos) {
            mMac.add(info.getMac());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mMac);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedMac = mMac.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void BackAction(View v) {
        finish();
        overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
    }

    /*String action = "";
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            action = intent.getAction();
            if (action.equals(MyService.ACTION_DISCONNECTED)) {
                handler.sendEmptyMessage(1);

            } else if (action.equals(MyService.ACTION_ADD_USER_RESULT)) {

                int add_result_num = intent
                        .getIntExtra(MyService.VALUE_INFO, 0);
                Message message = new Message();
                message.what = 2;
                message.obj = add_result_num;
                handler.sendMessage(message);

            }

        }
    };*/

    /**
     * 添加子账号
     *
     * @param v
     */
    String phoneNum = "";

    public void remotaAdd(View v) {

        if (!Util.hasNetwork(RemoteAddUserAvtivity.this)) {
            showToast(getText(R.string.no_network).toString());
            return;
        }
        if (TextUtils.isEmpty(edt_phonenum.getText())) {
            showToast(getText(R.string.input_phone).toString());
            return;
        }
        if (!Util.isMobileNO(edt_phonenum.getText().toString())) {
            showToast(getText(R.string.phone_format_wrong).toString());
            return;
        }
        if (isProgressing) {
            LogUtils.e(TAG, " isProgressing  return");


            return;
        }

        isProgressing = true;
        phoneNum = edt_phonenum.getText().toString();
        int userID =mySharedPreferences.getUserId();
        //TODO: 选择输入完成，保存成员账户信息,上传服务器
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("phoneNum", phoneNum);
        httpProgram.add("mac",selectedMac);
        httpProgram.add("user_id",userID+"");
        httpProgram.add("admin_psw","888888");
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/Login/addChildAccount");
        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onFailure(String s, IOException e) {
                showToast(getText(R.string.remote_add_fail).toString());
            }

            @Override
            public void onResponse(String string) {
                //把授权信息上传服务器， 参数有:用户id ,设备mac ,管理员密码， 被授权用户手机号码，
                showToast("添加用户成功".toString());

            }
        });

    }

    /**
     * 自定义提示
     *
     * @param str
     */
    Toast toast = null;

    void showToast(String str) {
        if (toast != null) {
            toast.cancel();
        }
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.toastshow, null);
        TextView textView = (TextView) view.findViewById(R.id.toastshow);
        textView.setText(str);
        toast = new Toast(this);
        double d = getResources().getDisplayMetrics().density;
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
    }


}
